<template>
  <DkCircleBackground>
    <view class="py4">
      <view class="mxa w-80% rounded-t-lg bg-yellow p2 text-center">{{ data.title }}</view>
      <view v-for="(item, index) in data.questions" :key="index">
        <view v-if="showIndex === index" class="m-x-a min-h-300px w-90% rounded-4 bg-white p3">
          <view class="p1 text-center text-14px text-gray">- 第 {{ index + 1 }} 题 -</view>
          <view class="pb5 pt2 text-center text-18px font-bold">{{ item.question }}</view>
          <view class="">
            <view
              v-for="(answer, k) in item.answers"
              :key="k"
              class="answer-option my3 flex items-center justify-between border-rounded-2 p3"
              :class="{ choose: chooseItem[index] && chooseItem[index].number === answer.number }"
              @click="onChoose(index, answer)"
            >
              <view class="py2">{{ answer.number }}、{{ answer.value }}</view>
              <view class="choose-circle size-25px flex items-center justify-center border-3 border-#F1EEF2 rounded-full border-solid">
                <view class="size-10px rounded-full" />
              </view>
            </view>
          </view>
          <view v-if="result" class="relative h-100px w-full" @click="handleClickAd()">
            <u-button shape="circle" class="animate__animated animate__pulse test-button" type="error"> 看广告，查看结果 </u-button>
          </view>
          <view class="flex items-center justify-between">
            <view>
              <u-button v-if="showIndex !== 0" class="w-120px" @click="onPrev()">上一题</u-button>
            </view>
            <view class="text-purple-7">
              第
              <text class="text-36px font-bold">{{ index + 1 }}</text>
              /{{ data.questions.length }} 题
            </view>
          </view>
        </view>
      </view>
      {{ chooseItem }}
      {{ result }}
    </view>
  </DkCircleBackground>
</template>

<script>
import { index } from '~/api/test'
import DkCircleBackground from '~/components/dk-circle-background/index.vue'
import { addResult } from '~/api/user_result'

export default {
  components: { DkCircleBackground },
  data() {
    return {
      value: '',
      showIndex: 0,
      chooseItem: {},
      // 数据
      id: 0,
      data: {},
      result: null,
    }
  },
  beforeUnmount(){
    console.log('销毁广告')
    if (this.ad){
      this.ad.offClose(this.closeHandler)
    }
  },
  onLoad(query) {
    this.id = query.id
    this.getIndex(this.id)
  },
  methods: {
    handleClickAd() {
      tt.showLoading()
      this.ad.show()
    },
    adInit(){
      // 创建实例
      this.ad = tt.createRewardedVideoAd({
        adUnitId: this.appConfig.base?.adUnitId,
      })
      // 监听错误
      this.ad.onError((err) => {
        tt.hideLoading()
        switch (err.errCode) {
          case 1004:
            // 无合适的广告
            break
          default:
          // 更多请参考错误码文档
        }
      })
      // 监听视频播放完成
      this.ad.onClose(this.closeHandler)
      // 预加载资源
      this.ad.load()
    },
    closeHandler(data) {
      tt.hideLoading()
      if (data.isEnded) {
        console.log('观看完视频')
        addResult(this.id, { chooseItem: this.chooseItem, result: this.result }, 'test').then((res) => {
          console.log(res)
          this.result = res.data
        })
      } else {
        console.log('未观看完视频')
      }
    },
    calculateResult() {
      let totalScore = 0
      // 计算总分
      for (const key in this.chooseItem) {
        if (Object.prototype.hasOwnProperty.call(this.chooseItem, key)) {
          totalScore += Number.parseInt(this.chooseItem[key].score, 10)
        }
      }
      // 匹配结果
      return this.data.results.find((result) => {
        const ruleRange = result.rule.split('-')
        const minScore = Number.parseInt(ruleRange[0], 10)
        const maxScore = ruleRange.length > 1 ? Number.parseInt(ruleRange[1], 10) : minScore

        // 处理单个值的情况
        if (ruleRange.length === 1) {
          return totalScore === minScore
        } else {
          return totalScore >= minScore && totalScore <= maxScore
        }
      })
    },
    // 上一项
    onPrev() {
      if (this.showIndex > 0) {
        // 这里不应该直接减1，应该找到上一题的索引
        for (let i = this.showIndex - 1; i >= 0; i--) {
          if (this.chooseItem[i]) {
            delete this.chooseItem[this.showIndex]
            this.showIndex = i
            this.result = null
            // 移除当前题目的选择
            return
          }
        }
      }
    },
    // 选择
    onChoose(index, answer) {
      if (this.result)
        return
      // 如果已到达最后一题并且该选项已被选择，则不执行任何操作
      if (this.showIndex === this.data.questions.length - 1 && this.chooseItem[index])
        return
      // 更新选择的答案
      this.chooseItem[index] = answer
      // 跳转结果
      if (answer.result !== 0) {
        this.result = this.data.results[answer.result - 1]
        return
      }
      // 跳转题目
      if (answer.question !== 0) {
        this.showIndex = answer.question - 1
        return
      }
      // 只有当当前不是最后一题时，才显示下一题
      if (this.showIndex < this.data.questions.length - 1) {
        this.showIndex = index + 1
      } else {
        // 最后一个计算结果
        this.result = this.calculateResult()
      }
    },
    // 事件
    getIndex(pid) {
      index(pid).then((res) => {
        console.log(res)
        this.data = res.data
        this.adInit()
      })
    },
  },
}
</script>

<style>
@import '@/uni_modules/dk-diy-page/components/dk-diy-box/animate.css';
</style>

<style scoped lang="scss">
.answer-option {
  border: 3px solid #F1EEF2;

  &.choose {
    background: #EAFEFF;
    border: 3px solid #404DB6;
    color: #5961A8;
    .choose-circle{
      border-color: #404DB6;
      .rounded-full {
        background: #404DB6;
      }
    }
  }
}
.test-button {
  position: absolute;
  left: 10%;
  right: 10%;
  top: 30px;
  animation-delay: 0s;
  animation-duration: 1s;
  animation-iteration-count: infinite;
}
</style>
